// pages/index/product-details/product-details.js
const request = require('../../../../../utils/request')
const WxParse = require('../../../../../wxParse/wxParse/wxParse.js')
const common = require('../../../../../utils/common')
let CodeUrlbg = request.BASE_URL + '/static/share/qrcode_head.png?new=1'; //背景图片
let shareTitle = request.BASE_URL + 'static/share/qrcode_head2.png?new=1'
Page({


	/**
	 * 页面的初始数据
	 */
	data: {
		//banner轮播
		imgUrls: [
			'/pages/images/banner-4.png',
			'/pages/images/banner-4.png',
			'/pages/images/banner-4.png'
		],
		indicatorDots: false, //默认不显示指示点
		autoplay: true, //默认自动切换
		interval2: 3000, //自动切换时间间隔
		duration: 1000, //滑动动画时长

		//轮播
		currentSwiper: 0,


		//这个是猜你喜欢轮播
		currentSwiperNav: 0,


		// 分享弹窗
		isShowShare: false,


		//加入购物车弹窗
		isShowCart: false,
		isShowCart_type: 1,



		goods_id: '', //商品id
		detailInfo: {}, //商品信息
		isPintuan: false, //是否为拼团
		pintuan_list: {}, //拼团信息
		pinTuanList: [],


		guigelist: [],
		morenGuige: {}, //默认规格
		currentTab: 0, // 选择规格
		num: 1, //选择数量

		search_goods: [
			
		], //猜你喜欢
		page:1,
		isLastPage:false,
    hour: '00',
    minute: '00',
    second: '00',
		cart_num: '', //购物车总数
		showPoster: false, //显示海报
		erweiMa: '',
		isAddCar: false,
		baseUrl:''
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.setData({
			goods_id: options.id,
			baseUrl:request.BASE_URL
		})
	},

	onShow() {
		this.getDetailInfo()
		this.getYouLike()
		this.getCartNum()
		// this.getErCode()
	},
	// swiper内容左右滑动切换触发
	swiperChange(e) {
		const current = e.detail.current;
		this.setData({
			currentSwiper: current, // 更新当前选中
		});
	},

	/**
	 * 这个是猜你喜欢轮播
	 * swiper内容左右滑动切换触发
	 */
	swiperChangeNav(e) {
		const currentNav = e.detail.current;
		this.setData({
			currentSwiperNav: currentNav, // 更新当前选中
		});
	},

	toHome() {
		wx.switchTab({
			url: '/pages/index/index',
			success: function (res) {
				// success
			},
			fail: function () {
				// fail
			},
			complete: function () {
				// complete
			}
		})
	},
  toCate(){
		wx.switchTab({
			url: '/pages/classification/classification',
		})
  },
	toCart() {
		wx.switchTab({
			url: '/pages/shoppingCart/shoppingCart',
		})
	},

	/**
	 * 分享弹窗
	 */
	showShareWindow() {
		this.setData({
			isShowShare: true
		})
	},
	hideShareWindow() {
		this.setData({
			isShowShare: false
		})
	},

	// 显示海报
	showPoster() {
		this.setData({
			showPoster: true
		})
		this.createMsg()

		this.hideShareWindow()

	},
	hidePosterWindow() {
		this.setData({
			showPoster: false
		})
	},
	// 绘制文字自动换行
	drawArticle(ctx, kl, width, x, y) {
		let chr = kl.split('') // 分割为字符串数组
		let temp = ''
		let row = []
		for (let a = 0; a < chr.length; a++) {
			if (ctx.measureText(temp).width < width) {
				temp += chr[a]
			} else {
				a--
				row.push(temp)
				temp = ''
			}
		}
		row.push(temp)

		for (var b = 0; b < row.length; b++) {
			// 控制最多显示2行
			if (b < 2) {
				ctx.fillText(row[b], x, y + b * 20);
			}
		}
		let _len = row.length > 2 ? 2 : row.length
		return y + (_len - 1) * 20
	},
	// canvas生成海报
	createMsg() {
		var that = this;
		var context = wx.createCanvasContext('mycanvas');
		var path = that.data.detailInfo.cover;
		var pathErweima = that.data.erweiMa
		let url1 = this.getImageInfo(path)
		let url2 = this.getImageInfo(pathErweima)
		Promise.all([url1, url2]).then(([url1, url2]) => {
			context.drawImage(url2.path, 20, 460, 130, 130)
			var name = that.data.detailInfo.name;
			// //绘制名字
			context.setFontSize(22);
			context.setFillStyle('#333333');
			context.setTextAlign('center');
			context.fillText(name, 90, 437);
			context.stroke();
			// 绘制右侧文字
			context.setFontSize(18);
			context.setFillStyle('#999999');
			context.setTextAlign('center');
			context.fillText('长按或扫描二维码', 230, 520);
			// 绘制右侧下方文字
			context.setFontSize(18);
			context.setFillStyle('#999999');
			context.setTextAlign('center');
			context.fillText('查看详情', 230, 550);
			context.stroke();
			context.drawImage(url1.path, 0, 0, 375, 400)
			context.save(); // 保存当前context的状态
			context.draw();
			//将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
			setTimeout(function () {
				wx.canvasToTempFilePath({
					canvasId: 'mycanvas',
					success: function (res) {
						var tempFilePath = res.tempFilePath;
						that.setData({
							imagePath: tempFilePath,
						});
					},
					fail: function (res) {
						console.log(res);
					}
				});
			}, 200);
		})
		// wx.getImageInfo({
		// 	src: pathErweima,
		// 	success: function (resp) {
		// 		context.drawImage(resp.path, 30, 440, 152, 152)
		// 		context.draw();
		// 	}
		// })
		// wx.getImageInfo({
		// 	src: path,
		// 	success: function (res) {
		// 		context.drawImage(res.path, 10, 10, 400, 598)
		// 		// var name = that.data.detailInfo.name;
		// 		// //绘制名字
		// 		// context.setFontSize(22);
		// 		// context.setFillStyle('#333333');
		// 		// context.setTextAlign('center');
		// 		// context.fillText(name, 120, 437);
		// 		// context.stroke();
		// 		// context.save(); // 保存当前context的状态
		// 		context.draw();
		// 	}
		// })



	},
	// 获取二维码
	getErCode() {
		request._post('/api?method=user.getposter', {
			source: 2,
			type: 2
		}).then(res => {
			this.setData({
				erweiMa: res.data
			})
		})
	},
	/**
	 * 加入购物车弹窗
	 */
	showCartWindow(e) {
		let type = e.currentTarget.dataset.type
		let addcar = e.currentTarget.dataset.addcar
		this.setData({
			isShowCart: true,
			isShowCart_type: type,
			isAddCar: addcar == 1 ? true : false
		})
	},
	hideCartWindow() {
		this.setData({
			isShowCart: false
		})
	},


	/**
	 * 规格
	 */
	switchNav(e) {
		const index = e.currentTarget.dataset.index;
		let item = e.currentTarget.dataset.item
		this.setData({
			currentTab: index, // 更新选中的tab
			morenGuige: item,
			num: 1
		});
	},


	/**
	 * 输入框事件
	 */
	bindManual: function (e) {
    var num = e.detail.value;
    if(this.data.detailInfo.is_pin && num >= this.data.detailInfo.max_nums){
      return getApp().toast('最多限购'+this.data.detailInfo.max_nums+'件')
    }
		this.setData({
			num: num
		});
	},

	// 获取详情页信息
	getDetailInfo() {
		let _this = this
		request._post('/api?method=goods.goodsinfo', {
			goods_id: this.data.goods_id
		}).then(res => {
      let list = res.data.products
      list.forEach((obj)=>{
        obj.addSwitch = false
        if (obj.cart_num) {
          obj.addSwitch = true
        }
      })
			_this.setData({
				detailInfo: res.data,
				isPintuan: res.data.is_pin,
				pintuanInfo: res.data.tuan,
				pintuan_list:  res.data.tuan ? res.data.tuan.pin_users :[],
        morenGuige: list ? list[0] :{},
        num: list ? list[0].cart_num > 0 ? list[0].cart_num : 1 : 1,
				guigelist: list,
			})
      console.log(res.data.intro)
			WxParse.wxParse('detail_content', 'html', res.data.intro, _this, 5);
			// 拼团倒计时
			_this.countDown()
      if (res.data.is_seckill) {
        _this.countDownTime(res.data.seckill_rule.etime)
        _this.getSeckillDraw(res.data)
      }else{
        _this.getDraw(res.data)
      }

		})
  },
  previewImg(e){
    var that = this
    var current = e.target.dataset.imgurl; // 获取当前点击的图片URL  
    wx.previewImage({  
      current: current, // 当前显示图片的http链接  
      urls: that.data.detailInfo.images // 需要预览的图片http链接列表  
    }); 
  },
	// 获取猜你喜欢
	getYouLike() {
		let _this = this
		request._post('/api?method=goods.goodslist', {
			xiaoqu: wx.getStorageSync('localXiaoqu') ? wx.getStorageSync('localXiaoqu').id : '',
			page:this.data.page,
			limit:3
		}).then(res => {
			if(res.data.length == 0) {
				_this.setData({
					isLastPage:true
				})
				return
			} 
			_this.setData({
				search_goods: res.data
			})
		})
	},
	changePage() {
		let page = this.data.page
		if(this.data.isLastPage ) {
			this.setData({
				page:1,
				isLastPage:false
			})
			this.getYouLike()
			return 
		}
		page++
		this.setData({
			page
		})
		this.getYouLike()
	},
	toDetail(e) {
		let item = e.currentTarget.dataset.item
		wx.navigateTo({
			url: '/pages/home/pages/my/product-details/product-details?id=' + item.goods_id,
		})
	},
	addNum(e) {
		let type = e.currentTarget.dataset.type
		let num = this.data.num
		let morenGuige = this.data.morenGuige
		if (type == 1) {
			// 减
			if (num == 1) {
				return getApp().toast('不能再减少了~')
			}
			num--
		} else {
			if (num >= morenGuige.kucun) {
				return getApp().toast('商品库存不足~')
      }
      if(this.data.detailInfo.is_pin && num >= this.data.detailInfo.max_nums){
        return getApp().toast('最多限购'+this.data.detailInfo.max_nums+'件')
      }
      if(this.data.detailInfo.is_seckill && num >= this.data.detailInfo.seckill_rule.max_nums){
        return getApp().toast('最多限购'+this.data.detailInfo.seckill_rule.max_nums+'件')
      }
			num++
		}
		this.setData({
			num
		})
	},
	// 查询购物车
	getCartNum() {
		request._post('api?method=goods.shoppingSum', {}, 'noload').then(res => {
			this.setData({
				cart_num: res.data ? res.data : ''
			})
			wx.setTabBarBadge({ //这个方法的意思是，为小程序某一项的tabbar右上角添加文本
				index: 3, //代表哪个tabbar（从0开始）
				text: res.data ? String(res.data) : '' //显示的内容
			})
		}).catch(res => {

		})
	},
	/**
	 *确认订单 
	 */
	confirmOrder() {
		let _this = this
		let morenGuige = this.data.morenGuige
		let isPintuan = this.data.isPintuan
		let isShowCart_type = this.data.isShowCart_type
		if (isPintuan && isShowCart_type == 2) {
			request._post('/api?method=merchants.pintuanCreate', {
				product_id: morenGuige.id,
				team_id: 0
			}).then(res => {
				getApp().toast('开团成功')
				getApp().globalData.changePoint = true
				setTimeout(function () {
					wx.reLaunch({
						url: '/pages/home/pages/my/confirm-order/confirm-order?id=' + res.data.card_is + "&type=" + 2,
					});
				}, 1000)
			})
		} else {
			request._post('/api?method=cart.add', {
				product_id: morenGuige.id,
        nums: this.data.num,
        num_type: 2,
				// num_type: _this.data.isAddCar ? 1 : 2,
				order_type: isShowCart_type == 2 ? 2 : 1,
				// item_id:
			}, 'noload').then(res => {
				if (_this.data.isAddCar) {
					getApp().toast('加购成功~')
					getApp().globalData.changePoint = true
					_this.getCartNum()
					_this.setData({
						isShowCart: false
					})
				} else {
					wx.navigateTo({
						url: '/pages/home/pages/my/confirm-order/confirm-order?id=' + res.data.cart_id + "&type=" + 1 + "&store_id=" + res.data.store_id,
					})
				}
			})
		}
  },
  // 倒计时
  countDownTime(endTime) {
    console.log('倒计时::'+endTime)
    if (!endTime) {
        return
    }
    let timer = setInterval(() => {
        //截止时间
        var obj = {}
        let time = endTime
        time--;
        let now = new Date().getTime();
        let diff = parseInt(time - now / 1000);
        
        if (diff < 0) {
            clearInterval(timer)
            this.setData({
                isCountDown: false
            })
        } else {
            let date = common.formattime(diff * 1000);
            this.setData({
                hour: date.hour,
                minute: date.minute,
                second: date.second
            })
            

        }

    }, 1000)
    this.setData({
        timer
    })
  },
	// 拼团列表倒计时
	countDown() {
		let _this = this
		let pintuan_list = this.data.pintuan_list
		if (!pintuan_list) {
			return
		}
		pintuan_list.forEach(function (obj, index) {
			if (!obj.close_time) {
				return
			}
			let timer = setInterval(() => {
				//截止时间
				let time = obj.close_time
				time--;
				let now = new Date().getTime();
				let diff = parseInt(time * 1000 - now / 1000);
				if (diff < 0) {
					clearInterval(timer)
				} else {
					let date = common.formattime(diff * 1000);
					pintuan_list[index]['hour'] = date.hour
					pintuan_list[index]['minute'] = date.minute
					pintuan_list[index]['second'] = date.second
					_this.setData({
						pintuan_list
					})
				}
			}, 1000)
		})

	},
	// 获取购物车数据
	getCartNum() {
		let _this = this
		request._post('api?method=goods.shoppingSum', {}).then(res => {
			_this.setData({
				cart_num: res.data ? res.data : ''
			})
		}).catch(res => {})
  },
  
  getDraw(detailInfo) {
    var no_product = {
      background: '#fff',
      width: '1296rpx',
      height: '1038rpx',
      views: [ 
      {
          type: 'image',
          url: detailInfo.posters || detailInfo.cover,
          css: {
            left: '229rpx',
            width: '838rpx',
            height: '838rpx',
            display: 'block'
          },
      },
        {
          type: 'text',
          text: '￥'+detailInfo.price,
          css: {
            top: '928rpx',
            left: '896rpx',
            textAlign: 'center',
            fontSize: '95rpx',
            fontWeight: '500',
            color: "#DF2A1B",
          },
        },
      ]
    }
    this.setData({
      template: no_product
    })
  },
  getSeckillDraw(detailInfo) {
    var no_product = {
      background: '#fff',
      width: '1296rpx',
      height: '1038rpx',
      views: [{
        type:'image',
        url: '/pages/images/product_share_bg.png',
        css: {
          left: '0',
          top: '0',
          right: 0,
          width: '1296rpx',
          height: '1036rpx',
          display: 'block'
        },
      },{
        type: 'text',
        text: '限时秒杀 售完即止',
        css: {
          top: '50rpx',
          left: '245rpx',
          textAlign: 'center',
          fontSize: '96rpx',
          fontWeight: '600',
          color: "#fff",
          letterSpacing: '4rpx'
        },
      },
      {
          type: 'image',
          url: detailInfo.posters || detailInfo.cover,
          css: {
            left: '86rpx',
            top: '265rpx',
            width: '606rpx',
            height: '606rpx',
            display: 'block',
            borderRadius: '33rpx'
          },
      },{
          type: 'text',
          text: '￥',
          css: {
            top: '344rpx',
            left: '745rpx',
            textAlign: 'center',
            fontSize: '75rpx',
            fontWeight: 'bold',
            color: "#DF2A1B"
          },
        },{
          type: 'text',
          text: detailInfo.is_seckill ? detailInfo.seckill_rule.seckill_price : detailInfo.price,
          css: {
            top: '304rpx',
            left: '825rpx',
            textAlign: 'center',
            fontSize: '125rpx',
            fontWeight: '500',
            color: "#DF2A1B"
          },
        },
        {
          type: 'text',
          text: detailInfo.is_seckill ? '￥'+detailInfo.price : Number(detailInfo.mktprice) > 0 && detailInfo.price !=  detailInfo.mktprice ? '￥'+detailInfo.mktprice : '',
          css: {
            top: '475rpx',
            left: '745rpx',
            textAlign: 'center',
            fontSize: '80rpx',
            fontWeight: '500',
            color: "#9FA0A0",
            textDecoration: 'line-through'
          },
        },
        {
          type: 'image',
          url: '/pages/images/qiang_btn.png',
          css: {
            left: '705rpx',
            top: '604rpx',
            width: '502rpx',
            height: '284rpx',
            display: 'block',
          },
      },
      {
        type: 'text',
        text: '— 今日15:00前下单，16:00前送达 —',
        css: {
          bottom: '40rpx',
          left: '96rpx',
          textAlign: 'center',
          fontSize: '60rpx',
          fontWeight: '400',
          color: "#fff",
          letterSpacing: '10rpx'
        },
      },
      ]
    }
    this.setData({
      template: no_product
    })
  },
  canvasSuc(e) {
    wx.hideLoading()
    console.log(e)
    this.setData({
      image: e.detail.path
    })
  },
	// 微信分享到朋友圈
	onShareTimeline() {
    return {
			title:this.data.detailInfo.goods_name,
      imageUrl:this.data.detailInfo.cover,
      // path:'pages/index/index'
      path: '/pages/home/pages/my/product-details/product-details?id='+this.data.detailInfo.goods_id,
		}
  },
	// 分享给朋友
	onShareAppMessage: function () {
    console.log(this.data.image)
		return {
			title:this.data.detailInfo.goods_name,
      imageUrl:this.data.image,
      // path:'pages/index/index'
      path: '/pages/home/pages/my/product-details/product-details?id='+this.data.detailInfo.goods_id,
		}
	},
	// 分享朋友圈
	toFrendCircle() {
		getApp().toast('请点击右上角 ... 分享至朋友圈')
	},
    /**
     * 加入购物车
     */

    add() {
      let goodsLinJu = this.data.morenGuige
      if (!goodsLinJu.addSwitch) {
        goodsLinJu.addSwitch = true
        goodsLinJu.cart_num++
      }
      this.addCartApi(goodsLinJu)
      this.setData({
        morenGuige:goodsLinJu
      })
  },
  // 购物车加减
  addCartReduce(e) {
      let type = e.currentTarget.dataset.type //1 减 2 加
      let item = this.data.morenGuige
      if (type == 1) {
        if(item.cart_num == 0) return
          item.cart_num--
      } else {
          item.cart_num++
      }
      this.addCartApi(item)
      this.setData({
        morenGuige:item
      })
  },
  addCartApi(item) {
    let _this = this
    let goodsLinJu = this.data.morenGuige
    request._post('/api?method=cart.add', {
        product_id: item.id,
        nums: item.cart_num,
        num_type: 2,
    }, 'noload').then(res => {
      if (item.cart_num == 0) {
        goodsLinJu.addSwitch = false
        this.setData({
          morenGuige: goodsLinJu
        })
      }
      _this.getCartNum()
    }).catch(res => {
        // 库存不足情况--
        let goodsLinJu = this.data.morenGuige
        goodsLinJu.cart_num--
        if (goodsLinJu.cart_num <= 0) {
            goodsLinJu.addSwitch = false
        }
        this.setData({
          morenGuige: goodsLinJu
        })
    })
  },

  /**
   * 输入框事件
   */
  bindManual: function (e) {
      var num = e.detail.value;
      this.setData({
        num: num
      });
  },
	//长按保存图片
	viewImage(e) {
		let srci = e.currentTarget.dataset.src
		let _this = this
		wx.getImageInfo({
			src: _this.data.imagePath,
			success(res) {
				let path = res.path
				wx.saveImageToPhotosAlbum({
					filePath: path,
					success(resp) {
						getApp().toast('保存成功，快快分享吧~')
						setTimeout(function () {
							_this.setData({
								showPoster: false
							})
						}, 1500)
					}
				})
			}
		})
	},
	getImageInfo(url) {
		return new Promise((resolve, reject) => {
			wx.getImageInfo({
				src: url,
				success: resolve,
				fail: reject,
			})
		})
	},
  onUnload(){
    let pages = getCurrentPages();
    let beforePage = pages[pages.length -2];  //获取上个页面的实例对象
    beforePage.shuaxin();
  }

})